package com.flea.hclv.controller;

import com.alibaba.fastjson.JSON;
import com.flea.hclv.model.dao.HVisitorOrderRelationMapper;
import com.flea.hclv.model.entity.HVisitor;
import com.flea.hclv.model.entity.HVisitorOrder;
import com.flea.hclv.model.entity.HVisitorOrderRelation;
import com.flea.hclv.model.entity.vo.ProductTimeTableVo;
import com.flea.hclv.service.HServicePayRebackItemService;
import com.flea.hclv.service.HVisitorOrderService;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.bean.FleaPage;
import com.flea.system.entity.OrgDept;
import com.flea.system.platform.session.FleaOrgUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: project
 * @description: 地接社游客订单
 * @author: shiliqiang
 * @create: 2018-10-13 17:51
 * @version: 1.0
 */
@Controller
@RequestMapping("/flea/hclv/visitor/order")
public class HVisitorOrderController {

    private static final Logger logger = LoggerFactory
            .getLogger(HVisitorOrderController.class);

    @Autowired
    private HVisitorOrderService orderService;
    private HServicePayRebackItemService hServicePayRebackItemService;


    // 下单
    @RequestMapping("place_an_order")
    @ResponseBody
    public ServerResponse<ProductTimeTableVo> placeAnOrder(String timeTableId) {
        return orderService.placeAnOrder(timeTableId);
    }

    @RequestMapping("createOrder")
    @ResponseBody
    public ServerResponse<Map<String, String>> createOrder(
            HttpServletRequest request, String model) {
        String userId = FleaOrgUtils.getCurUserUuid(request);
        OrgDept currentUserDept = FleaOrgUtils.getCurrentUserDept(request);
        if (model == null) {
            return ServerResponse.createByErrorMessage("model为空");
        }
        List<String> visitorIds = new ArrayList<>();
        visitorIds.add("1");
        visitorIds.add("2");
        ProductTimeTableVo productVo = JSON.parseObject(model,
                ProductTimeTableVo.class);
        String paymentPersonId = "";
        return orderService.createOrder(userId, currentUserDept, productVo,
                visitorIds, paymentPersonId);
    }

    @RequestMapping("pay")
    @ResponseBody
    public ServerResponse<String> pay(String model, HttpServletRequest request) {
        HVisitorOrder order = JSON.parseObject(model, HVisitorOrder.class);
        String userId = FleaOrgUtils.getCurUserUuid(request);

        return orderService.pay(order, userId);
    }

    @RequestMapping("cancel")
    @ResponseBody
    public ServerResponse<String> cancel(String orderNo,HttpServletRequest request) {
        String userId = FleaOrgUtils.getCurUserUuid(request);
      try {
        return orderService.cancel(orderNo, userId);
      } catch (Exception e) {
        return ServerResponse.createByErrorMessage(e.getMessage());
      }
    }

    @ResponseBody
    @RequestMapping("order_list")
    public ServerResponse<List<HVisitorOrder>> list(HttpServletRequest request) {
        String userId = FleaOrgUtils.getCurUserUuid(request);
        return orderService.selectOrderList(userId);
    }

    /**
     * 当点击进行下单，传递的内容，班期id，下单人数（成人人数，儿童人数，其他人数·，然后创建一个订单）
     *
     * @param
     * @description TODO
     * @methodName qyeryForOder
     * @returnType ServerResponse<HProduct>
     * @throw
     */
    @RequestMapping("loadOrder")
    @ResponseBody
    public ServerResponse<HVisitorOrder> addOrder(
            HttpServletRequest request, @RequestParam("model") String model) {
        // selectForUpdate 查询并修改班期表数据
        ServerResponse<HVisitorOrder> result = null;
        logger.info("传入游客订单json:{}", model);
        try {
            result = orderService.addOrder(request,model);
        } catch (Exception e) {
            logger.error("游客订单：", e);
            e.printStackTrace();
            return ServerResponse.createByErrorMessage(e.getMessage());
        }
        // 判断是否需要创建团的概念
        // 创建订单

        return result;

    }

    /**
     * 当点击进行下单，传递的内容，班期id，OrderId，下单人数（成人人数，儿童人数，其他人数·，然后创建一个订单）
     *
     * @param
     * @description TODO
     * @methodName qyeryForOder
     * @returnType ServerResponse<HProduct>
     * @throw
     */
    @RequestMapping("updateOrder")
    @ResponseBody
    public ServerResponse<HVisitorOrder> updateOrder(
            HttpServletRequest request, @RequestParam("model") String model) {
        // selectForUpdate 查询并修改班期表数据
        ServerResponse<HVisitorOrder> result = null;
        try {
            result = orderService.updateOrder(request,
                    model);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMessage(e.getMessage());
        }
        // 判断是否需要创建团的概念
        // 创建订单

        return result;

    }

    /**
     * @param
     * @description 获取所有当前部门的订单信息, 查询条件可以为:订单号，起止时间，订单状态，订单创建人
     * @methodName getAllVisitorListByOrgId
     * @returnType ServerResponse<HVisitorOrder>
     * @throw
     */
    @ResponseBody
    @RequestMapping("listOrgOder")
    public ServerResponse<FleaPage<HVisitorOrder>> getAllVisitorListByOrgId(HttpServletRequest request, FleaPage<HVisitorOrder> paging/*@Param("model")String model*/) {
        String model = request.getParameter("model");
        ServerResponse<FleaPage<HVisitorOrder>> result = orderService.findVisitorOderByOrgId(request, model, paging.getCurPage(), paging.getPageSize());
        return result;

    }
    @ResponseBody
    @RequestMapping("listCompleteVisiterOrder")
    public ServerResponse<FleaPage<HVisitorOrder>> getAlllistNoCompleteVisiterOrderByUserId(HttpServletRequest request, FleaPage<HVisitorOrder> paging/*@Param("model")String model*/) {
        String model = request.getParameter("model");
        ServerResponse<FleaPage<HVisitorOrder>> result = orderService.getAlllistCompleteVisiterOrder(request, model, paging.getCurPage(), paging.getPageSize());
        return result;

    }
    @ResponseBody
    @RequestMapping("listNoCompleteVisiterOrder")
    public ServerResponse<FleaPage<HVisitorOrder>> getAllNoCompleteVisitorListByUserId(HttpServletRequest request, FleaPage<HVisitorOrder> paging/*@Param("model")String model*/) {
        String model = request.getParameter("model");
        ServerResponse<FleaPage<HVisitorOrder>> result = orderService.getAllNoCompleteVisitorListByUserId(request, model, paging.getCurPage(), paging.getPageSize());
        return result;
    }

    @ResponseBody
    @RequestMapping("listOrderVisitors")
    public ServerResponse<List<HVisitor>> getVisitorsByOrderId(HttpServletRequest request) {
        String orderNo = request.getParameter("model");
        ServerResponse<List<HVisitor>> result = orderService.findVisitorsByOrderId(request, orderNo);
        return result;

    }

    /**
     * 更新游客订单状态1、关闭订单
     *
     * @param
     * @throws Exception
     * @description 业务描述：1、只有未支付的订单可进行点击订单关闭
     * @methodName updateVisitorStatus
     * @returnType ServerResponse<List   <   HVisitor>>
     * @throw
     */
    @ResponseBody
    @RequestMapping("closeOrder")
    public ServerResponse<List<HVisitorOrder>> updateVisitorStatusToClose(HttpServletRequest request) {
        String model = request.getParameter("model");

        ServerResponse<List<HVisitorOrder>> result = null;
        try {
            result = orderService.updateVisitorStatusToClose(request, model);
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage(e.getMessage());
        }
        return result;

    }

    /**
     * 更新游客订单状态 订单完成
     *
     * @param
     * @throws Exception
     * @description 业务描述：只有支付完成的订单可进行点击完成，完成之后不可进行任何的修改
     * @methodName updateVisitorStatus
     * @returnType ServerResponse<List   <   HVisitor>>
     * @throw
     */
    @ResponseBody
    @RequestMapping("setSuccessOrder")
    public ServerResponse<List<HVisitorOrder>> updateVisitorStatusToOk(HttpServletRequest request) {
        String orderNo = request.getParameter("model");
        ServerResponse<List<HVisitorOrder>> result = null;
        try {
            result = orderService.updateVisitorStatusToOk(request, orderNo);
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage(e.getMessage());
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("cancelOrder")
    public ServerResponse<String> updateVisitorStatusToCancel(HttpServletRequest request) {
        String orderNo = request.getParameter("model");
        ServerResponse<String> result = null;
        try {
            result = orderService.updateVisitorStatusToCancel(request, orderNo);
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage(e.getMessage());
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("findDetailById")
    public ServerResponse<HVisitorOrder> findDetailById(HttpServletRequest request) {
        String orderId = request.getParameter("model");
        ServerResponse result = null;
        try {
            result = orderService.findOrderDetailById(orderId);

        } catch (Exception e) {
            return ServerResponse.createByErrorMessage(e.getMessage());
        }
        return result;
    }
    //根据每个团，获取每个团的订单信息,进行分页
    @ResponseBody
    @RequestMapping("findListByGroupId")
  public ServerResponse<HVisitorOrder> findListByGroupId(HttpServletRequest request,FleaPage<HVisitor> paging){
      String model = request.getParameter("model");
    try {
      ServerResponse result =  orderService.findByGroupId(model,request,paging.getCurPage(),paging.getPageSize());
      return result;
    } catch (Exception e) {
      e.printStackTrace();
      return ServerResponse.createByErrorMessage(e.getMessage());
    }
  }

  /**
   * 需要参数为订单orderNo，原用户id：oldVisitorId  新用户Id:newOrderId
   * @return
   */
  @ResponseBody
  @RequestMapping("updateVisitorByOrderId")
  public ServerResponse<HVisitorOrder> updateVisitorByOrderId(HttpServletRequest request){
    String model = request.getParameter("model");
    try {
    ServerResponse result = orderService.updateVisitorByOrderId(model,request);
      return result;
    } catch (Exception e) {
      e.printStackTrace();
      return ServerResponse.createByErrorMessage(e.getMessage());
    }
  }
  /**
   * 需要参数为订单orderNo，用户id：oldVisitorId
   * @return
   */
  @ResponseBody
  @RequestMapping("delVisitorByOrderNoAndVisitorId")
  public ServerResponse<HVisitorOrder> delVisitorByOrderId(HttpServletRequest request){
    String model = request.getParameter("model");
    try {
      ServerResponse result = orderService.delVisitorByOrderNoAndVisitorId(model,request);
      return result;
    } catch (Exception e) {
      e.printStackTrace();
      return ServerResponse.createByErrorMessage(e.getMessage());
    }
  }





    // @RequestMapping("alipayCallback.do")
    // @ResponseBody
    // public Object alipayCallback(HttpServletRequest request){
    // Map<String,String> params= Maps.newHashMap();
    //
    // Map<String,String[]> requestParams =request.getParameterMap();
    // for (Iterator iterator = requestParams.keySet().iterator();
    // iterator.hasNext();){
    // String key=(String)iterator.next();
    // String[] values= requestParams.get(key);
    // String valueStr="";
    // for (int i=0;i< values.length;i++){
    // valueStr=(i==values.length-1)?valueStr+values[i]:valueStr+values[i]+",";
    // }
    // params.put(key,valueStr);
    // }
    // logger.info("支付宝回调，sign:{},trade_status:{},参数:{}",params.get("sign"),params.get("trade_status"),params.toString());
    //
    // //验证回调的正确性，是不是只是支付宝发的，并且还要避免重复通知
    //
    // params.remove("sign_type");
    // try {
    // boolean alipayRSACheckedV2= AlipaySignature.rsaCheckV2(params,
    // Configs.getAlipayPublicKey(),"utf-8",Configs.getSignType());
    //
    // if (!alipayRSACheckedV2){
    // return ServerResponse.createByErrorMessage("非法请求，验证不通过");
    // }
    // } catch (AlipayApiException e) {
    // logger.error("支付宝验证回调异常",e);
    // }
    //
    // //
    //
    // //业务逻辑
    // ServerResponse serverResponse=orderService.aliCallback(params);
    // if (serverResponse.isSuccess()){
    // return Const.AlipayCallback.RESPONSE_SUCCESS;
    // }
    // return Const.AlipayCallback.RESPONSE_FAILED;
    // }
    //
    // @RequestMapping("query_order_pay_status.do")
    // @ResponseBody
    // public ServerResponse<Boolean> queryOrderPayStatus(HttpServletRequest
    // request, String orderNo){
    // String userId = FleaOrgUtils.getCurUserUuid(request);
    // ServerResponse
    // serverResponse=iOrderService.queryOrderPayStatus(userId,orderNo);
    // if (serverResponse.isSuccess()){
    // return ServerResponse.createBySuccess(true);
    // }
    //
    // return ServerResponse.createBySuccess(false);
    //
    //
    //
    //
    //
    //
}
